{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d6ef6479-b2ba-42e9-8e0e-bea7f535a8bc",
   "metadata": {},
   "source": [
    "Chapter 05\n",
    "\n",
    "# 马氏距离\n",
    "Book_6《数据有道》 | 鸢尾花书：从加减乘除到机器学习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dfd8a1aa-0e15-4e5d-94d1-c91d022a3f7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.spatial import distance\n",
    "import numpy as np\n",
    "from numpy.linalg import inv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "384bbf81-052d-47f6-9f23-b4d3288fdde4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Variance-covariance matrix\n",
    "SIGMA = np.array([[2, 1], [1, 2]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cdd13e51-5b97-40f1-902b-7773f3f863dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "q   = [0, 0];       # query point\n",
    "x_1 = [-3.5, -4];   # data point 1\n",
    "x_2 = [2.75, -1.5]; # data point 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f6dfd618-5465-45fa-ac09-088520220d99",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Calculate Mahal distances\n",
    "\n",
    "d_1 = distance.mahalanobis(q, x_1, inv(SIGMA))\n",
    "d_2 = distance.mahalanobis(q, x_2, inv(SIGMA))\n",
    "\n",
    "# Note1: the output of the function is Mahal distance, not Mahal distance squared\n",
    "# Note2: input is the inverse of the covariance matrix"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
